package com.vg.login;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.androidhive.jsonparsing.Activity_ChatIndex;
import com.androidhive.jsonparsing.AndroidDashboardDesignActivity;
import com.androidhive.jsonparsing.JSONParser;
import com.androidhive.jsonparsing.MyAdapter;
import com.androidhive.jsonparsing.R;
import com.vg.config.linkUrl;
import com.vg.leftmenu.register_1;
import com.vg.library.Httppostaux;
import com.vg.service.ServiceBody;
import com.vg.service.ServiceCity;
import com.vg.service.ServiceColor;
import com.vg.service.ServiceDrinker;
import com.vg.service.ServiceEducation;
import com.vg.service.ServiceGender;
import com.vg.service.ServiceMaritalStatus;
import com.vg.service.ServiceMyHeight;
import com.vg.service.ServiceMyWeight;
import com.vg.service.ServiceReligion;
import com.vg.service.ServiceSmoker;
import com.vg.service.ServiceUserType;
import com.vg.spinner.Student;

public class Login extends Activity {

	EditText user, pass;
	Button blogin, register;
	// TextView registrar;
	Httppostaux post;
	String IP_Server = "deduocyeu.com/json";
	String URL_connect = "http://" + IP_Server + "/droidlogin/acces.php";

	boolean result_back;
	private ProgressDialog pDialog;
	String id = "";
	String email = "";
	String use_login = "";
	String fullname = "";
	String picture = "";
	com.vg.service.ServiceCity mCity_service;
	ArrayList<Student> arrayList = new ArrayList<Student>();

	MyAdapter adapter;
	JSONParser jparse;
	JSONArray jsa;
	linkUrl mUrl;

	private ArrayList<Student> array;
	private static final String PHRASE = "Item_";
	private String prefBody = "PrefBody";
	private String prefCity = "PrefCity";
	private String prefColor = "PrefColor";
	private String prefDrinker = "PrefDrinker";
	private String prefEducation = "PrefEducation";
	private String prefGender = "PrefGender";
	private String prefMaritalStatus = "PrefMaritalStatus";
	private String prefHeight = "PrefHeight";
	private String prefWeight = "PrefWeight";
	private String prefReligion = "PrefReligion";
	private String prefSmoker = "PrefSmoker";
	private String prefUsertype = "PrefUsertype";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_ac);

		post = new Httppostaux();
		mUrl = new linkUrl();
		// post = new Httppostaux();
		// Intent it = new Intent(this, service_loadjson.class);
		// it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// startService(it);

		// Button bt_register=(Button)findViewById(R.id.bt_register_login1);
		// bt_register.setOnClickListener(new OnClickListener() {
		//
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// Intent i=new Intent(Login.this,Register.class);
		// startActivity(i);
		// }
		// });

		// Intent it1 = new Intent(this, com.vg.service.ServiceCity.class);
		// it1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// startService(it1);
		//
		// mCity_service = new com.vg.service.ServiceCity();
		// arrayList = mCity_service.dropSpinner();
		// Log.i("test12345", String.valueOf(arrayList));
		// Toast.makeText(getApplicationContext(), "" +
		// String.valueOf(arrayList),
		// Toast.LENGTH_SHORT).show();

		user = (EditText) findViewById(R.id.edusuario);
		pass = (EditText) findViewById(R.id.edpassword);
		blogin = (Button) findViewById(R.id.Blogin);

		blogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				getWindow().setSoftInputMode(
						WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

				String username = user.getText().toString();
				String password = pass.getText().toString();

				if (username.equals("") || password.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Vui Lòng Nhập Thông Tin!",
							Toast.LENGTH_SHORT).show();
				}

				int susscess = -1;

				/*
				 * Creamos un ArrayList del tipo nombre valor para agregar los
				 * datos recibidos por los parametros anteriores y enviarlo
				 * mediante POST a nuestro sistema para relizar la validacion
				 */
				ArrayList<NameValuePair> postparameters2send = new ArrayList<NameValuePair>();

				postparameters2send.add(new BasicNameValuePair("email",
						username));
				postparameters2send.add(new BasicNameValuePair("password",
						password));

				// realizamos una peticion y como respuesta obtenes
				// un array
				// JSON
				JSONObject jdata = post.getserverdata_object(
						postparameters2send,
						"http://deduocyeu.com/json/login.php");

				/*
				 * como estamos trabajando de manera local el ida y vuelta sera
				 * casi inmediato para darle un poco realismo decimos que el
				 * proceso se pare por unos segundos para poder observar el
				 * progressdialog la podemos eliminar si queremos
				 */
				SystemClock.sleep(950);

				// si lo que obtuvimos no es null
				if (jdata != null && jdata.length() > 0) {

					JSONObject json_data = null; // creamos un objeto JSON
					try {
						susscess = jdata.getInt("susscess");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (susscess == 0) {
						Log.e("loginstatus ", "invalido");
						err_login();
					} else {
						final ProgressDialog pdRing = ProgressDialog.show(
								Login.this, null, null);
						pdRing.setContentView(R.layout.custom_dialog_login);
						pdRing.setCancelable(true);
						new Thread(new Runnable() {
							public void run() {
								// TODO Auto-generated method stub
								try {
//									putPref(prefBody, mUrl.body_type);
//									putPref(prefCity, mUrl.city);
//									putPref(prefColor, mUrl.color);
//									putPref(prefDrinker, mUrl.drinker);
//									putPref(prefEducation, mUrl.education);
//									putPref(prefGender, mUrl.gender);
//									putPref(prefMaritalStatus, mUrl.marital_status);
//									putPref(prefHeight, mUrl.my_height);
//									putPref(prefWeight, mUrl.my_weight);
//									putPref(prefReligion, mUrl.religion);
//									putPref(prefSmoker, mUrl.smoker);
//									putPref(prefUsertype, mUrl.user_type);
									
									Log.e("loginstatus ", "valido");
									Intent i = new Intent(Login.this,
											Activity_ChatIndex.class);
									String use = "tuan".toString();
									i.putExtra("use_id", id);
									i.putExtra("use_login", use);
									i.putExtra("use_fullname", fullname);
									i.putExtra("use_avatar", picture);
									Log.e("ID", id);
									startActivity(i);
								} catch (Exception e) {
								}
								pdRing.dismiss();
							}
						}).start();
					}
				} else {
					Toast.makeText(getApplicationContext(), "Loi Json ",
							Toast.LENGTH_SHORT).show();
				}

			}
		});

		register = (Button) findViewById(R.id.register_login);
		register.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(Login.this, register_1.class);
				startActivity(i);
			}
		});

	}

	public void err_login() {
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(200);
		Toast toast1 = Toast.makeText(getApplicationContext(),
				"Enter Email and password is wrong", Toast.LENGTH_SHORT);
		toast1.show();
	}

	public boolean checklogindata(String username, String password) {
		if (username.equals("") || password.equals("")) {
			Log.e("Login ui", "checklogindata user or pass error");
			return false;
		} else {
			return true;
		}
	}

	public void putPref(String pref, String url) {
		jparse = new JSONParser();
		jsa = jparse.getJsonarray(url);
		SharedPreferences prefs;
		prefs = getSharedPreferences(pref, MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		for (int i = 0; i < jsa.length(); i++) {
			try {
				editor.putString(PHRASE + i + "", jsa.getString(i));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		editor.commit();
	}
}
